﻿using System;
using System.ComponentModel;
using System.Reflection;

namespace Jy.Extensions;

public static class EnumExtensions
{
    /// <summary>
    /// 获取枚举描述值
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string GetDesc(this Enum obj)
    {
        var type = obj.GetType().GetField(obj.ToString());
        var attr = type.GetCustomAttribute<DescriptionAttribute>();
        if (attr != null)
            return attr.Description;
        return type.Name;
    }

    /// <summary>
    /// 获取枚举描述值
    /// </summary>
    public static string GetDesc(this object obj, bool defaultUseName = true)
    {
        var type = obj.GetType().GetField(obj.ToString());
        if (type == null)
            return null;
        var attr = type.GetCustomAttribute<DescriptionAttribute>();
        if (attr != null)
            return attr.Description;
        if (defaultUseName)
            return type.Name;
        return null;
    }
}

